import io from 'socket.io-client'

import {
  reqRegister,
  reqLogin,
  reqUpdate,
  reqUser,
  reqUserList,
  reqMessagelist,
  reqReadMessage
} from '../api'

import {
  AUTH_SUCCESS,
  ERR_MES,
  RECEIVE_USER,
  RESET_USER,
  RECEIVE_USER_LIST,
  RECEIVE_MESSAGE_LIST,
  RECEIVE_NEW_MESSAGE,
  READ_MESSAGE
} from './action-types'


/* 
  同步action
*/

// 授权成功的同步action
const authSuccess = (user)=>({type: AUTH_SUCCESS, data: user})

// 错误提示信息的同步action
const errMsg = (message)=>({type: ERR_MES, data: message})

// 更新用户信息成功的同步action
const receiveUser = (user)=>({type: RECEIVE_USER, data: user})

// 更新用户信息失败的同步action
export const resetUser = (message)=>({type: RESET_USER, data: message})

// 获取用户列表
const receiveUserList = (userList)=>({type: RECEIVE_USER_LIST, data: userList})

// 获取用户消息列表
const receiveMessageList = ({users, chatMsgs, userId})=>({type: RECEIVE_MESSAGE_LIST, data: {users, chatMsgs, userId}})

// 收到新消息
const receiveNewMessage = (message, userId)=>({type: RECEIVE_NEW_MESSAGE, data: {message, userId}})

// 修改未读为已读返回数量
const readMessage = (count, from, userId) => ({type: READ_MESSAGE, data: {count, from, userId}})





/* 
  异步action
*/

// 注册异步action
export function register(userInfo) {
  return async function(dispatch){
    // 发送异步请求
    const response = await reqRegister(userInfo);
    const result = response.data;
    if (result.code === 0) { // 注册成功
      const userId = result.data._id
      getMessageList(dispatch, userId) // 注册成功即登录成功，获取消息列表
      dispatch(authSuccess(result.data))
    } else { // 失败
      dispatch(errMsg(result.msg))
    }
  }
}

// 登录异步action
export function login(userInfo) {
  return async function(dispatch){
    // 发送异步请求
    const response = await reqLogin(userInfo);
    const result = response.data;
    if (result.code === 0) { // 登录成功
      const userId = result.data._id
      getMessageList(dispatch, userId) // 获取消息列表
      dispatch(authSuccess(result.data))
    } else {
      dispatch(errMsg(result.msg))
    }
  }
}

// 更新用户信息异步action
export const updateUserInfo = (userInfo) => {
  return async dispatch => {
    const response =  await reqUpdate(userInfo)
    const result = response.data;
    if (result.code === 0) { // 更新成功，获得新的信息
      dispatch(receiveUser(result.data))
    } else { // 失败
      dispatch(resetUser(result.msg))
    }
  }
}

// 获取用户信息异步action
export const getUserInfo = () => {
  return async dispatch => {
    const response = await reqUser()
    const result = response.data
    if (result.code === 0) { // 获取成功
      const userId = result.data._id
      getMessageList(dispatch, userId) // 自动登录成功，获取消息列表
      dispatch(receiveUser(result.data))
    } else { // 失败
      dispatch(resetUser(result.msg))
    }
  }
}

// 获取用户列表
export const getUserList = (userType) => {
  return async dispatch => {
    const response = await reqUserList(userType)
    const result = response.data
    if (result.code === 0) {
      dispatch(receiveUserList(result.data))
    }
  }
}

// 发送消息
export const sendMessage = ({from, to, content}) => {
  return dispatch => {
    sendMesg({from, to, content})
  }  
}

// 修改未读为已读
export const modifyReadStatue = (from, userId) => {
  return async dispatch => {
    const response = await reqReadMessage(from)
    const result = response.data
    if (result.code === 0) {
      dispatch(readMessage(result.data, from, userId))
    }
  }
}



/* 
  工具函数
*/

// 获取消息列表 (用户登录成功后调用)
async function getMessageList(dispatch, userId) {
  // 进入此函数时已成功登录，连接服务端socket
  connectSocket(dispatch, userId)
  const response = await reqMessagelist()
  const result = response.data
  if (result.code === 0) {
    const {users, chatMsgs} = result.data
    dispatch(receiveMessageList({users, chatMsgs, userId}))
  }
}

// socket 连接与监听
const connectSocket = (dispatch, userId) => {
  console.log('登录成功，socket已连接服务器！！')
  if (!io.socket) {
    // 与服务端连接
    io.socket = io('ws://localhost:4000')

    // 监听接收的数据
    io.socket.on('receiveMsg', (message)=>{
      // 当收到与自己相关的消息时才调用同步action修改chat状态
      if (message.from === userId || message.to === userId) {
        dispatch(receiveNewMessage(message, userId))
        // 判断当前是否正在消息所在的聊天页面，是否修改为已读
        const pathArry = window.location.href.split('/')
        const fromId = pathArry[pathArry.length - 1]
        if (message.from === fromId && !message.read) {
          reqReadMessage(fromId).then((res)=> {
            if (res.data.code === 0) {
              dispatch(readMessage(res.data.data, fromId, userId))
            }
          })
        }
      }
    })
  }
}

// socket 向后台发消息
const sendMesg = ({from, to, content}) => {
  io.socket.emit('sendMsg', {from, to, content})
}